﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Virvar.Net.Cryptography
{
    public class Encryptor
    {
        Encoding enc = Encoding.Default;
        RSACryptoServiceProvider rsaProvide;

        public Encryptor(string xmlPublicKey, Encoding enc)
        {
            this.enc = enc;
            rsaProvide = new RSACryptoServiceProvider();
            // загружаем открытый ключ
            rsaProvide.FromXmlString(xmlPublicKey);
        }

        // шифрование сообщения
        public byte[] EncryptData(string dataToSend)
        {
            byte[] clearText = enc.GetBytes(dataToSend);
            //int maxLength = rsaProvider.KeySize / 8 - 42;
            int maxLength = rsaProvide.KeySize / 8 - 11;
            int iterCount = clearText.Length / maxLength;
            List<byte> bytesToSend = new List<byte>(rsaProvide.KeySize / 8 * iterCount);
            for (int i = 0; i <= iterCount; i++)
            {
                byte[] tempBytes = new byte[Math.Min(clearText.Length - i * maxLength, maxLength)];
                Buffer.BlockCopy(clearText, i * maxLength, tempBytes, 0, tempBytes.Length);
                bytesToSend.AddRange(rsaProvide.Encrypt(tempBytes, false));
            }
            return bytesToSend.ToArray();
        }

        // шифрование сообщения
        public byte[] EncryptData(byte[] dataToSend)
        {
            //int maxLength = rsaProvider.KeySize / 8 - 42;
            int maxLength = rsaProvide.KeySize / 8 - 11;
            int iterCount = dataToSend.Length / maxLength;
            List<byte> bytesToSend = new List<byte>(rsaProvide.KeySize / 8 * iterCount);
            for (int i = 0; i <= iterCount; i++)
            {
                byte[] tempBytes = new byte[Math.Min(dataToSend.Length - i * maxLength, maxLength)];
                Buffer.BlockCopy(dataToSend, i * maxLength, tempBytes, 0, tempBytes.Length);
                bytesToSend.AddRange(rsaProvide.Encrypt(tempBytes, false));
            }
            return bytesToSend.ToArray();
        }
    }
}
